package service

import (
	"context"
	"errors"
	"zhonghui/console/models"
)

func GetEmployees(accessToken string) ([]Employee, error) {
	employees := []Employee{}
	departments, err := GetDepartmentList(accessToken)
	if err != nil {
		return nil, err
	}
	if departments.Errcode != 0 {
		return nil, errors.New(departments.Errmsg)
	}
	for _, department := range departments.Department {
		employeeList, err := GetEmployeeList(accessToken, department.ID)
		if err != nil {
			return nil, err
		}
		if employeeList.Errcode != 0 {
			return nil, errors.New(employeeList.Errmsg)
		}
		employees = append(employees, employeeList.UserList...)
	}
	return employees, nil
}

type Users struct {
	Name       string `json:"name"`
	OpenUserId string `json:"open_userid"`
	UserId     string `json:"userid"`
}

func CreateEmployee(store models.Store, contactId int64, corpId string, users []Users, welcome string) error {
	return store.ExecTx(context.Background(), func(q *models.Queries) error {
		err := q.InvalidContactEmployee(context.Background(), contactId)
		if err != nil {
			return err
		}
		for _, user := range users {
			employeeId, err := q.CreateEmployee(context.Background(), models.CreateEmployeeParams{
				Name:        user.Name,
				Phone:       "",
				Avatar:      "",
				AvatarThumb: "",
				Corpid:      corpId,
				UserID:      user.UserId,
				OpenUserID:  user.OpenUserId,
				Welcome:     welcome,
			})
			if err != nil {
				return err
			}
			err = q.CreateContactEmployee(context.Background(), models.CreateContactEmployeeParams{
				ContactID:  contactId,
				EmployeeID: employeeId,
				Status:     "valid",
			})
			if err != nil {
				return err
			}
		}
		return nil
	})
}
